package com.juc.learn.reentrantlock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ClassName:Test
 * Package:com.juc.learn.reentrantlock
 * Description:
 *
 * @Author:@郭先森
 * @Create:2025/7/27 - 10:12
 * @Version:v1.0
 */
//可重入锁：synchronized（隐式的）和Lock（显式的）都是可重入锁
//可重入锁也叫做递归锁
public class Test {
    public static void main(String[] args) throws InterruptedException {
        //演示
        Object obj = new Object();
        new Thread(()->{
            synchronized (obj){
                System.out.println(Thread.currentThread().getName()+"外层");
                synchronized (obj){
                    System.out.println(Thread.currentThread().getName()+"中层");
                    synchronized (obj){
                        System.out.println(Thread.currentThread().getName()+"内层");
                    }
                }
            }
        },"线程1").start();

        //Lock演示可重入锁
        Lock lock = new ReentrantLock();
        new Thread(()->{
            try {
                //上锁
                lock.lock();
                System.out.println(Thread.currentThread().getName()+"： 外层");
                try {
                    lock.lock();
                    System.out.println(Thread.currentThread().getName()+"： 内层");
                }finally {
                   lock.unlock(); //假设这不解锁，会有问题，比如在下边我进行新建一个线程操作的时候会有问题
                }
            }finally {
                //释放锁
                lock.unlock();
            }
        },"线程2").start();

        new Thread(()->{
           lock.lock();
            System.out.println("******");
            lock.unlock();
        }).start();

    }
}
